<template>
  <a-select
    showSearch
    :disabled="disabled"
    :getPopupContainer="getParentContainer"
    :placeholder="placeholder"
    v-model="selectedValue"
    style="width: 100%;"
    :filterOption="filterOption"
    @change="handleAsyncChange"
    allowClear
  >
    <a-select-option v-for="d in options" :key="d.value" :value="d.value">{{ d.text }}</a-select-option>
  </a-select>

</template>

<script>
import {getAction} from '@api/manage'
import {ajaxGetDictItems, getDictItemsFromCache, serviceAjaxGetDictItems, sysAjaxGetDictItems} from '@/api/api'
export default {
  name: 'JSearchSelect',
  props: {
    disabled: Boolean,
    value: [String, Number],
    dict: String,
    placeholder: {
      type: String,
      default: '请选择',
      required: false
    },
    popContainer: {
      type: String,
      default: '',
      required: false
    },
    pageSize: {
      type: Number,
      default: 10,
      required: false
    }
  },
  data() {
    return {
      selectedValue: undefined,
      options: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if(this.dict){
          this.initDictData()
        }
        if (val) {
          this.selectedValue = val
        } else {
          this.selectedValue = undefined
        }
      }
    },
    dict: {
      handler(val) {
        if(val){
          this.initDictData()
        }
      },
      immediate: true
    },
  },
  methods: {
    initDictData() {
      let dictStr=""
      //根据字典Code, 初始化字典数组
          if (this.dict) {
            let arr = this.dict.split(',')
            if (arr[0].indexOf('where') > 0) {
              let tbInfo = arr[0].split('where')
              dictStr = tbInfo[0].trim() + ',' + arr[1] + ',' + arr[2] + ',' + encodeURIComponent(tbInfo[1])
            } else {
              dictStr = this.dict
            }
            if (this.dict.indexOf(',') == -1) {
              //优先从缓存中读取字典配置
              if (getDictItemsFromCache(this.dict)) {
                this.options = getDictItemsFromCache(this.dict)
                return
              }
            }
            // --------------------------update-begin author:liujb date:20220330 解决分库找不到表问题----------------------------------
            let dictCode = this.dict;
            if (dictCode && dictCode.indexOf(',') != -1) {
              //关联表字典（举例：sys_user,realname,id）
              let dictCodeSplit = this.dict.split(","); //以，分割
              let tableName = dictCodeSplit[0];
              let tableNameSplit = tableName.split("_");
              //以上注释代码做如下改动，是为了避免以后增加服务后，还要再修改这块的代码。开闭原则 modified by wuzx 20220601
              if (tableNameSplit && tableNameSplit.length > 0 && tableNameSplit[0] && tableNameSplit[0] != 'sys'&& tableNameSplit[0] != 'ext') {
                serviceAjaxGetDictItems(tableNameSplit[0], dictCode).then((res) => {
                  if (res.success) {
                    this.options = res.result;
                  }
                });
              } else {
                ajaxGetDictItems(dictCode).then((res) => {
                  if (res.success) {
                    this.options = res.result;
                  }
                });
              }
            }else{
              //根据字典Code, 初始化字典数组
              sysAjaxGetDictItems(this.dict, null).then((res) => {
                if (res.success) {
                  this.options = res.result;
                }
              })
            }
          }
      // getAction(`/api/erpmng/sys/dict/getDictItems/${this.dict}`, {pageSize: this.pageSize, keyword: ''}).then(res => {
      //   if (res.success) {
      //     this.options = res.result
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleAsyncChange(value) {
      this.selectedValue = value
      this.$emit('change', this.selectedValue)
    },
    getParentContainer(node) {
      if (!this.popContainer) {
        return node.parentNode
      } else {
        return document.querySelector(this.popContainer)
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped></style>
